package com.coffee.web.config;

import com.coffee.web.interceptor.LoginCheckInterceptor;
import com.coffee.web.interceptor.LoginSatutsInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nullable;
import java.util.Date;


@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
	@Autowired
	LoginCheckInterceptor loginCheckInterceptor;
	@Autowired
	LoginSatutsInterceptor loginSatutsInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
		registry.addInterceptor(loginSatutsInterceptor).addPathPatterns("/**");
	}

//	/**
//	 * 静态资源访问
//	 */
//	@SuppressWarnings("all")
//	@Override
//	public void addResourceHandlers(ResourceHandlerRegistry registry) {
//		if (!registry.hasMappingForPattern("/static/**")) {
//			registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//		}
//	}

	/**
	 * 404页面配置
	 */
	@SuppressWarnings("Convert2Lambda")
	@Bean
	public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
		return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
			@Override
			public void customize(ConfigurableWebServerFactory factory) {
				// 走的是页面路由接口，而非页面模板
				ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
				factory.addErrorPages(error404Page);
			}
		};
	}

	/**
	 * 字符串转日期
	 */
	@Bean
	public Converter<String, Date> dateConverter() {
		return new Converter<String, Date>() {
			@Override
			public Date convert(@Nullable String dateString) {
				if (StringUtils.isBlank(dateString)) {
					return null;
				} else if (NumberUtils.isParsable(dateString)) {
					// 时间戳
					return new Date(Long.parseLong(dateString));
				} else {
					// yyyy-MM-dd HH:mm:ss
					// yyyy-MM-dd
					// ......
					return new Date();
				}
			}
		};
	}

}
